<template>
  <view class="water-monitor-layout">
    <!-- 左侧区域-水表树形结构 -->
    <view class="aside-panel" :class="{ collapsed: isAsideCollapsed }">
      <view class="aside-header">
        <view class="collapse-btn" @click="toggleAside">
          <uni-icons
            :type="isAsideCollapsed ? 'right' : 'left'"
            size="20"
            color="#409eff"
          ></uni-icons>
        </view>
        <uni-icons v-if="!isAsideCollapsed" type="location-filled" size="18" color="#409eff"></uni-icons>
        <text v-if="!isAsideCollapsed" class="header-title">每日用水量</text>
      </view>
      
      <!-- 树形结构 -->
      <scroll-view v-if="!isAsideCollapsed" scroll-y class="tree-container" :show-scrollbar="true">
        <uni-load-more v-if="treeLoading" status="loading" content-text="加载区域与水表数据中..."></uni-load-more>
        <view v-else>
          <view v-for="node in treeData" :key="node.id">
            <tree-item 
              :node="node" 
              :level="0"
              :selected-id="selectedNode?.id"
              @node-click="handleNodeSelect"
            />
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 右侧主内容区 -->
    <view class="main-content">
      <!-- 时间筛选栏 -->
      <view class="time-filter-bar">
        <!-- 时间选择 -->
        <view class="date-picker-group">
          <uni-datetime-picker 
            v-model="dateRange" 
            type="daterange"
            rangeSeparator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            @change="handleDateChange"
            :clear-icon="false"
          />
        </view>
        
        <!-- 快捷时间按钮 -->
        <view class="quick-time-group">
          <button class="quick-btn" size="mini" type="primary" @click="setQuickTime('today')">今日</button>
          <button class="quick-btn" size="mini" type="primary" @click="setQuickTime('yesterday')">昨天</button>
          <button class="quick-btn" size="mini" type="primary" @click="setQuickTime('week')">本周</button>
          <button class="quick-btn" size="mini" type="primary" @click="setQuickTime('month')">当月</button>
          <button class="quick-btn" size="mini" type="primary" @click="setQuickTime('lastMonth')">上月</button>
        </view>
        
        <!-- 基准线控制 -->
        <view class="dayUsage-line-control">
          <uni-switch
            v-model="showdayUsageLine"
            active-color="#409eff"
            @change="onDayUsageLineChange"
          ></uni-switch>
          <text class="switch-text">{{ showdayUsageLine ? '显示基准线' : '隐藏基准线' }}</text>
          <text class="dayUsage-tip" v-if="!dayUsage">（当前水表无基准用量）</text>
        </view>
      </view>

      <!-- 标签页切换 -->
      <uni-segmented-control 
        :current="activeTab === 'chart' ? 0 : 1" 
        :values="['折线图', '表格']" 
        @clickItem="onTabChange"
        styleType="button"
        activeColor="#409eff"
        class="tab-control"
      />

      <!-- 数据展示区域 -->
      <view class="data-container">
        <!-- 图表展示 -->
        <view class="chart-container" v-if="activeTab === 'chart'">
          <uni-load-more v-if="chartLoading" status="loading" content-text="加载每日用水数据中..."></uni-load-more>
          <view v-else-if="!isChartEmpty" class="chart-wrapper">
            <qiun-data-charts
              :key="chartKey"
              type="line"
              :opts="chartOpts"
              :chartData="chartData"
              canvasId="dayFlow"
            />
          </view>

          <view v-else class="empty-tip">
            <uni-icons type="info-filled" size="32" color="#909399"></uni-icons>
            <text class="empty-text">请选择水表并设置日期范围查询每日数据</text>
          </view>
        </view>

        <!-- 表格展示 -->
        <scroll-view scroll-y class="table-container" v-if="activeTab === 'table'">
          <uni-load-more v-if="tableLoading" status="loading" content-text="加载每日数据中..."></uni-load-more>
          <view v-else-if="tableData.length > 0" class="table-wrapper">
            <view class="table-row table-header">
              <text class="table-cell">日期</text>
              <text class="table-cell">当日用水量(吨)</text>
            </view>
            <view class="table-row" v-for="(item, index) in tableData" :key="index">
              <text class="table-cell">{{ formatDateTime(item.analyseDate) }}</text>
              <text class="table-cell">{{ item.todayUsage }}</text>
            </view>
          </view>
          <view v-else class="empty-tip">
            <uni-icons type="info-filled" size="32" color="#909399"></uni-icons>
            <text class="empty-text">当前日期范围内无每日数据</text>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<script setup>
import qiunDataCharts from '@/uni_modules/qiun-data-charts/components/qiun-data-charts/qiun-data-charts.vue'
import { watch } from 'vue'
import { ref, computed, onMounted } from 'vue'
import dayjs from 'dayjs'
// 引入API方法
import { listArea } from '@/api/water/area'
import { listElement } from '@/api/water/element'
import { listMeterAnalyse } from '@/api/water/meterAnalyse'  // 每日分析数据API
// 引入树组件
import TreeItem from '../../../components/TreeItem/TreeItem.vue'


// ======================== 响应式数据 ========================
const currentPage = ref(1)
const pageSize = ref(50)
const totalData = ref([])

const treeData = ref([])
const selectedNode = ref(null)
const dateRange = ref([])

const treeLoading = ref(false)
const chartLoading = ref(false)
const tableLoading = ref(false)

const activeTab = ref('chart') // chart: 图表, table: 表格
const tableData = ref([])

// 基准线控制相关
const showdayUsageLine = ref(true)  // 基准线显示开关
const dayUsage = ref(null)          // 当前选中水表的基准值

// 图表配置 (使用 uCharts)
const chartData = ref({})
const chartKey = ref(0)
const chartOpts = ref({
  color: ['#409EFF', '#f56c6c'],
  padding: [15, 15, 0, 5],
  enableScroll: false,
  legend: {
    show: true,
    position: 'top-right',
    itemWidth: 12,
    itemHeight: 12,
    textStyle: {
      fontSize: 12,
      color: '#333'
    }
  },
  xAxis: {
    disableGrid: true,
    scrollShow: false,
    itemCount: 0,
    rotateLabel: true,
    labelAngle: 45
  },
  yAxis: {
    gridType: 'dash',
    dashLength: 2,
    data: [{
      min: 0,
      title: '当日用水量(吨)'
    }]
  },
  extra: {
    line: {
      type: 'curve',
      width: 2,
      activeType: 'hollow'
    }
  }
})


const isChartEmpty = computed(() => {
  return !chartData.value.series || chartData.value.series.length === 0 || chartData.value.series[0].data.length === 0
})

const isAsideCollapsed = ref(false)
const toggleAside = () => {
  isAsideCollapsed.value = !isAsideCollapsed.value
  // 延迟强制图表重新渲染,等待动画完成
  setTimeout(() => {
    chartKey.value++
  }, 350)
}

// ======================== 页面初始化 ========================
onMounted(() => {
  initAreaMeterTree()
  setQuickTime('month')  // 默认显示当月数据
})

// ======================== 树形结构逻辑 ========================
const initAreaMeterTree = async () => {
  treeLoading.value = true
  try {
    const areaRes = await listArea({ pageNum: 1, pageSize: 1000 })
    if (areaRes.code !== 200) throw new Error('获取区域数据失败')
    
    const meterRes = await listElement({ pageNum: 1, pageSize: 1000 })
    if (meterRes.code !== 200) throw new Error('获取水表数据失败')

    const areaTree = buildAreaTree(areaRes.rows)
    const finalTree = assignMetersToArea(areaTree, meterRes.rows)

    treeData.value = finalTree
  } catch (err) {
    uni.showToast({
      title: err.message || '初始化数据失败',
      icon: 'none'
    })
  } finally {
    treeLoading.value = false
  }
}

const buildAreaTree = (areas) => {
  const areaMap = new Map()
  const rootAreas = []

  areas.forEach(area => {
    areaMap.set(area.id, {
      ...area,
      type: 'area',
      label: area.areaName,
      children: []
    })
  })

  areaMap.forEach(area => {
    const parentId = area.parentAreaId
    if (!parentId || parentId === 0 || !areaMap.has(parentId)) {
      rootAreas.push(area)
    } else {
      const parentArea = areaMap.get(parentId)
      parentArea.children.push(area)
    }
  })

  return rootAreas
}

const assignMetersToArea = (areaTree, meters) => {
  const [meterWithArea, meterWithoutArea] = meters.reduce((acc, meter) => {
    const hasFirstArea = !['', null, undefined].includes(meter.firstAreaId)
    const hasNegativeArea = !['', null, undefined].includes(meter.negativeAreaId)

    if (hasFirstArea || hasNegativeArea) {
      acc[0].push(meter)
    } else {
      acc[1].push(meter)
    }
    return acc
  }, [[], []])

  const traverse = (nodes) => {
    nodes.forEach(node => {
      if (node.type === 'area') {
        const matchedMeters = meterWithArea.filter(meter => {
          return meter.firstAreaId === node.id || meter.negativeAreaId === node.id
        }).map(meter => {
          const isNegativeMeter = meter.negativeAreaId === node.id
          return {
            ...meter,
            type: 'meter',
            label: isNegativeMeter ? `${meter.elemName}-反向表` : meter.elemName,
            children: null
          }
        })

        node.children = [...node.children, ...matchedMeters]

        if (node.children && node.children.length > 0) {
          traverse(node.children)
        }
      }
    })
  }

  traverse(areaTree)

  if (meterWithoutArea.length > 0) {
    const otherArea = {
      id: 'other_area_placeholder',
      type: 'area',
      label: '其他(无区域的水表)',
      children: meterWithoutArea.map(meter => ({
        ...meter,
        type: 'meter',
        label: meter.elemName,
        children: null
      }))
    }
    areaTree.push(otherArea)
  }

  return areaTree
}

const handleNodeSelect = (node) => {
  if (node.type === 'meter') {
    selectedNode.value = node
    // 从选中的水表节点中获取基准值
    dayUsage.value = node.dayUsage !== undefined && node.dayUsage !== null
      ? Number(node.dayUsage)
      : null
    fetchDailyData()
    // 立即更新基准线
    updatedayUsageMarkLine()
  }
}

// ======================== 时间筛选逻辑 ========================
const setQuickTime = (type) => {
  let endTime = dayjs().format('YYYY-MM-DD')
  let startTime = ''

  switch (type) {
    case 'today':
      startTime = dayjs().format('YYYY-MM-DD')
      endTime = dayjs().format('YYYY-MM-DD')
      break
    case 'yesterday':
      startTime = dayjs().subtract(1, 'day').format('YYYY-MM-DD')
      endTime = dayjs().subtract(1, 'day').format('YYYY-MM-DD')
      break
    case 'week':
      startTime = dayjs().startOf('week').add(1, 'day').format('YYYY-MM-DD')
      endTime = dayjs().endOf('week').add(1, 'day').format('YYYY-MM-DD')
      break
    case 'month':
      startTime = dayjs().startOf('month').format('YYYY-MM-DD')
      endTime = dayjs().endOf('month').format('YYYY-MM-DD')
      break
    case 'lastMonth':
      startTime = dayjs().subtract(1, 'month').startOf('month').format('YYYY-MM-DD')
      endTime = dayjs().subtract(1, 'month').endOf('month').format('YYYY-MM-DD')
      break
  }

  dateRange.value = [startTime, endTime]
  if (selectedNode.value) fetchDailyData()
}

const handleDateChange = () => {
  if (selectedNode.value) fetchDailyData()
}

const onTabChange = (e) => {
  activeTab.value = e.currentIndex === 0 ? 'chart' : 'table'
}

const onDayUsageLineChange = () => {
  updatedayUsageMarkLine()
}

// ======================== 数据查询逻辑 ========================
const fetchDailyData = async () => {
  if (!selectedNode.value || !dateRange.value[0] || !dateRange.value[1]) {
    uni.showToast({
      title: '请先选择水表并设置日期范围',
      icon: 'none'
    })
    return
  }

  chartLoading.value = true
  tableLoading.value = true
  currentPage.value = 1
  totalData.value = []
  const pageSizeVal = pageSize.value
  let hasMoreData = true

  try {
    while (hasMoreData) {
      const params = {
        meterId: selectedNode.value.id,
        startTime: dateRange.value[0],
        endTime: dateRange.value[1],
        pageNum: currentPage.value,
        pageSize: pageSizeVal
      }

      const res = await listMeterAnalyse(params)
      if (res.code !== 200 || !Array.isArray(res.rows)) {
        throw new Error(`第${currentPage.value}页每日数据请求失败`)
      }

      const currentPageData = res.rows
      totalData.value.push(...currentPageData)

      hasMoreData = currentPageData.length === pageSizeVal
      currentPage.value++
    }

    const sortedData = totalData.value.sort((a, b) => {
      return new Date(a.analyseDate) - new Date(b.analyseDate)
    })

    // 更新图表数据
    updateChartData(sortedData)

    // 更新表格数据
    tableData.value = sortedData

    if (sortedData.length === 0) {
      uni.showToast({
        title: '当前日期范围内无每日用水数据',
        icon: 'none'
      })
    }

  } catch (err) {
    uni.showToast({
      title: err.message || '每日用水数据查询失败',
      icon: 'none'
    })
  } finally {
    chartLoading.value = false
    tableLoading.value = false
    // 数据加载完成后更新基准线
    updatedayUsageMarkLine()
  }
}

const updateChartData = (data) => {
  chartData.value = {
    categories: data.map(item => dayjs(item.analyseDate).format('MM-DD')),
    series: [{
      name: '每日用水',
      data: data.map(item => item.todayUsage)
    }]
  }
}

const formatDateTime = (dateTime) => {
  return dayjs(dateTime).format('YYYY-MM-DD')
}

/**
 * 更新基准用量线配置
 */
const updatedayUsageMarkLine = () => {
  if (!chartData.value || !chartData.value.series || chartData.value.series.length === 0) {
    return
  }

  // 准备基准线数据
  let baselineSeries = []
  let legendData = ['每日用水']
  let baselineName = ''
  
  // 处理基准线名称和数据
  if (dayUsage.value !== null && !isNaN(dayUsage.value)) {
    baselineName = `基准用量线：${dayUsage.value.toFixed(2)} 吨`
    legendData.push(baselineName)
    
    if (showdayUsageLine.value) {
      // 创建与日期对应的基准线数据点
      const baselineData = chartData.value.categories.map(() => dayUsage.value)
      baselineSeries = [{
        name: baselineName,
        data: baselineData,
        type: 'line',
        lineStyle: {
          width: 2,
          type: 'solid'
        },
        itemStyle: {
          opacity: 0 // 隐藏基准线的数据点
        }
      }]
    }
  } else {
    baselineName = '基准用量线（无数据）'
    legendData.push(baselineName)
  }

  // 更新图表数据
  chartData.value = {
    ...chartData.value,
    series: [chartData.value.series[0], ...baselineSeries]
  }

  // 更新图表配置
  chartOpts.value = {
    ...chartOpts.value,
    legend: {
      ...chartOpts.value.legend,
      data: legendData
    },
    // 调整Y轴范围
    yAxis: {
      ...chartOpts.value.yAxis,
      data: [{
        ...chartOpts.value.yAxis.data[0],
        min: 0,
        max: calculateYAxisMax()
      }]
    }
  }

  // 强制图表重新渲染
  chartKey.value++
}

/**
 * 计算Y轴最大值
 */
const calculateYAxisMax = () => {
  if (!chartData.value || !chartData.value.series || !chartData.value.series[0]) {
    return null
  }

  const dataMax = Math.max(...chartData.value.series[0].data.filter(val => val !== null && !isNaN(val)), 0)
  const baselineValue = dayUsage.value !== null && !isNaN(dayUsage.value) ? dayUsage.value : 0
  const maxValue = Math.max(dataMax, baselineValue)
  
  return maxValue > 0 ? maxValue * 1.05 : 1 // 增加5%的余量
}

// 监听基准线开关和基准值变化 → 实时更新图表
watch([showdayUsageLine, dayUsage], () => {
  updatedayUsageMarkLine()
}, { immediate: true })

watch(chartData, (newData) => {
  const len = newData?.categories?.length || 0
  const itemCount = len > 15 ? 15 : len

  chartOpts.value = {
    ...chartOpts.value,
    xAxis: {
      ...chartOpts.value.xAxis,
      itemCount,
      scrollShow: false,
    }
  }

  chartKey.value++
}, { deep: true })
</script>

<style scoped>
.water-monitor-layout {
  display: flex;
  height: 100vh;
  background-color: #f5f5f5;
}

.aside-panel {
  width: 280px;
  background-color: #ffffff;
  border-right: 1px solid #e9ecef;
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
  transition: width 0.3s ease;
}

.aside-panel.collapsed {
  width: 40px;
}

.aside-header {
  display: flex;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #e9ecef;
}

.collapse-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  margin-right: 8px;
}

.header-title {
  margin-left: 8px;
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.tree-container {
  flex: 1;
  overflow-y: auto;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 15px;
  background-color: #ffffff;
  overflow: hidden;
}

.time-filter-bar {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.date-picker-group {
  flex: 1;
  min-width: 300px;
}

.quick-time-group {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.quick-btn {
  flex-shrink: 0;
}

/* 基准线控制样式 */
.dayUsage-line-control {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-left: auto;
  white-space: nowrap;
}

.switch-text {
  font-size: 14px;
  color: #606266;
}

.dayUsage-tip {
  font-size: 12px;
  color: #909399;
}

.tab-control {
  margin-bottom: 15px;
}

.data-container {
  flex: 1;
  overflow: hidden;
}

.chart-container,
.table-container {
  height: 100%;
}

.chart-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.table-wrapper {
  width: 100%;
}

.table-row {
  display: flex;
  border-bottom: 1px solid #ebeef5;
}

.table-header {
  background-color: #f5f7fa;
  font-weight: bold;
}

.table-cell {
  flex: 1;
  padding: 12px;
  text-align: center;
  font-size: 14px;
  border-right: 1px solid #ebeef5;
}

.table-cell:last-child {
  border-right: none;
}

.empty-tip {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
}

.empty-text {
  margin-top: 10px;
  font-size: 14px;
}

/* 适配小屏幕 */
@media (max-width: 1200px) {
  .dayUsage-line-control {
    margin-left: 0;
    margin-top: 8px;
    width: 100%;
    justify-content: flex-start;
  }
}
</style>